package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/8/17.<br><br>
 *
 * 中等：两两交换链表中的节点
 */
public class Topic24 {

    public static void main(String[] args) {
        Topic24 instance = new Topic24();

        int[] array = new int[] {1,2,3,4,5};
        ListNode head = Util.createList(array);
        Util.printList(instance.swapPairs(head));

        array = new int[] {1};
        head = Util.createList(array);
        Util.printList(instance.swapPairs(head));

        array = new int[] {1,2};
        head = Util.createList(array);
        Util.printList(instance.swapPairs(head));

        array = new int[] {1,2,3,4};
        head = Util.createList(array);
        Util.printList(instance.swapPairs(head));
    }

    public ListNode swapPairs(ListNode head) {
        if(head == null) {
            return null;
        }

        ListNode start = new ListNode(0);
        start.next = head;

        ListNode pre = start;
        ListNode node1 = head;
        ListNode node2 = head.next;

        while (node2 != null && node1 != null) {
            node1.next = node2.next;
            node2.next = node1;
            pre.next = node2;

            pre = node1;
            node1 = pre.next;
            if(pre.next != null) {
                node2 = pre.next.next;
            }
        }

        return start.next;
    }
}
